define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/selllist/index' + location.search,
                    add_url: 'ykjp/sell/selllist/add',
                    edit_url: 'ykjp/sell/selllist/edit',
                    del_url: 'ykjp/sell/selllist/del',
                    multi_url: 'ykjp/sell/selllist/multi',
                    details_url: "ykjp/sell/selllist/Detail",
                    goodsok_url: "ykjp/sell/selllist/goodsok",
                    table: 'ykjp_sell',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [{
                            checkbox: true
                        },
                        // {field: 'id', title: __('Id')},
                        {
                            field: 'code',
                            title: __('Code')
                        },
                        {
                            field: 'billing_time',
                            title: __('Billing_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime,
                            datetimeFormat: "YYYY-MM-DD"
                        },
                        {
                            field: 'customer_name',
                            title: __('Customer_name')
                        },
                        {
                            field: 'real_money',
                            title: __('Real_money'),
                            operate: 'BETWEEN'
                        },
                        {
                            field: 'status_list',
                            title: __('Status_list'),
                            searchList: {
                                "-1": __('Status_list -1'),
                                "1": __('Status_list 1'),
                                "2": __('Status_list 2'),
                                "3": __('Status_list 3'),
                                "4": __('Status_list 4'),
                                "5": __('Status_list 5'),
                                "6": __('Status_list 6'),
                                "7": __('Status_list 7'),
                                "8": __('Status_list 8'),
                                "9": __('Status_list 9'),
                                "10": __('Status_list 10')
                            },
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        // {field: 'customer_info_id', title: __('Customer_info_id')},
                        // {field: 'linkman', title: __('Linkman')},
                        // {field: 'phone', title: __('Phone')},
                        // {field: 'delivery_time', title: __('Delivery_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'type', title: __('Type'), searchList: {"1":__('Type 1'),"2":__('Type 2'),"3":__('Type 3')}, formatter: Table.api.formatter.normal},
                        // {field: 'purman_id', title: __('Purman_id')},
                        // {field: 'city', title: __('City')},
                        // {field: 'address', title: __('Address')},
                        // {field: 'total_nums', title: __('Total_nums')},
                        // {field: 'rate', title: __('Rate'), operate:'BETWEEN'},
                        // {field: 'theory_money', title: __('Theory_money'), operate:'BETWEEN'},
                        // {field: 'firmid', title: __('Firmid')},
                        // {field: 'admin_id', title: __('Admin_id')},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate',
                            width: "150px",
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'addtabs',
                                    title: __('look'),
                                    classname: 'btn btn-xs btn-primary  btn-addtabs',
                                    icon: 'fa fa-pencil-square-o',
                                    url: $.fn.bootstrapTable.defaults.extend.details_url,
                                }, {
                                    name: 'yes',
                                    title: __('Status_list 10'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-leaf',
                                    url: $.fn.bootstrapTable.defaults.extend.goodsok_url,
                                    hidden: function (row) {
                                        if (row.status_list == 6 || row.status_list == 7 || row.status_list == 8 || row.status_list == 9) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    },
                                    success: function (data, ret) {
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                        layer.msg('确认订单完成成功', {
                                            time: 2000, //2s后自动关闭
                                            end: function () {
                                                location.reload();
                                            }
                                        })
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }],
                            formatter: Table.api.formatter.operate
                        },
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'ykjp/sell/selllist/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [{
                            checkbox: true
                        },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'ykjp/sell/selllist/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'ykjp/sell/selllist/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            // Form.api.bindevent("form[role=form]");
            $('#myModal').on('show.bs.modal', function (e) {
                Controller.customer();
            });

            $('#myModal').on('hidden.bs.modal', function () {
                $('#table1').bootstrapTable('destroy');
            });
            //显示客户列表
            $("#c-supplier").focus(function () {
                $("#myModal").modal("show");
            });

            $('#modelProduct').on('show.bs.modal', function (e) {
                var btn = $(e.relatedTarget)
                Controller.getProduct(btn);
            });

            $('#modelProduct').on('hidden.bs.modal', function () {
                $('#table2').bootstrapTable('destroy');
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        },
        customer: function () {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/sell/index?a=1'
                }
            });

            var table = $("#table1");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                columns: [
                    [{
                            field: 'name',
                            title: __('Name')
                        },
                        {
                            field: 'contact',
                            title: __('Contact')
                        },
                        {
                            field: 'phone',
                            title: __('Phone')
                        },
                        {
                            field: 'description',
                            title: __('Description')
                        },
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/sell/sell/getCustomerByid',
                                    success: function (data, ret) {
                                        $("#c-supplier").val(data.row.name);
                                        $("#c-supId").val(data.row.id);
                                        $("#c-contact").val(data.row.contact);
                                        $("#c-phone").val(data.row.phone);
                                        $("#c-address").val(data.row.address);
                                        $("#c-city").citypicker("reset");
                                        if (data.city != "") {

                                            $("#c-city").citypicker("destroy");
                                            $("#c-city").citypicker({
                                                province: data.city[0],
                                                city: data.city[1],
                                                district: data.city[2]
                                            });

                                        }
                                        $('#myModal').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }, ],
                            formatter: function (value, row, index) {
                                if (row.status == '禁用') {
                                    return '该客户已禁用'
                                } else {
                                    var buttons = $.extend([], this.buttons || []);
                                    return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
                                }
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        getProduct: function (btn) {
            Table.api.init({
                extend: {
                    index_url: 'ykjp/sell/sell/index?a=2'
                }
            });

            var table = $("#table2");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                escape: false,
                columns: [
                    [{
                            field: 'name',
                            title: __('Name')
                        },
                        {
                            field: 'specification',
                            title: __('Specification')
                        },
                        {
                            field: 'sku',
                            title: __('Sku')
                        },
                        {
                            field: 'prop',
                            title: __('Prop'),
                            formatter: function (value, row, index) {
                                var str = "";
                                if (row.prop != "") {
                                    var arr = JSON.parse(row.prop);
                                    console.log(arr[0]);

                                    for (var i = 0; i < arr.length; i++) {

                                        if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                            str += arr[i]['title'] + ":" + arr[i]['value'] + ";<br>";
                                        }
                                    }
                                }
                                return str;
                            }
                        }, {
                            field: 'inventory',
                            title: __('Inventory')
                        },
                        {
                            field: 'operate',
                            width: "120px",
                            title: __('Selected'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'ajax',
                                    text: __('Selected'),
                                    title: __('Selected'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'ykjp/purchase/addorder/getProductByid',
                                    success: function (data, ret) {
                                        var _this = btn.parent().parent();
                                        _this.find('.inventory').text(data.row.inventory)
                                        _this.find(".find").val(data.row.name);
                                        _this.find(".find").attr("data-id", data.row.id);
                                        _this.find(".unit").text(data.row.unit);
                                        _this.find("td:eq(1)").text(data.row.sku);
                                        _this.find("td:eq(3)").text(data.row.specification);
                                        if (data.row.prop != "") {
                                            var arr = JSON.parse(data.row.prop);
                                            var str = "";
                                            for (var i = 0; i < arr.length; i++) {
                                                if (typeof (arr[i]['value']) != "undefined" && arr[i]['value'] !== null) {
                                                    str += arr[i]['title'] + ":" + arr[i]['value'] + "; <br>";
                                                }
                                            }
                                            _this.find("td:eq(4)").html(str);
                                        }
                                        $('#modelProduct').modal('hide');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }, ],
                            formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });
            Table.api.bindevent(table);

        }
    };
    return Controller;
});

// 删除行
function delRow(obj) {

    if ($('#table tbody tr').length == 2) {
        alert(__("Can't delete"));
        return false;
    }
    $(obj).parent().parent().remove();
    setnums();
    totalNums(null);
    calTotalMoneys()

}

//设置序号
function setnums() {
    var len = $('#table tr').length;
    for (var i = 1; i < len - 1; i++) {
        $('#table tr:eq(' + i + ') td:first').text(i);
    }
}

// 添加
function addRow() {
    var len = $('#table tr').length - 1;
    var lens = len - 2;
    var tempTr = '<tr>' +
            '<td>' + len + '</td>' +
            '<td></td>' +
            '<td><input  data-id="" type="text" name="" class="find" data-toggle="modal" data-target="#modelProduct" data-rule=""></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td class="unit"></td>' +
            '<td class="inventory"></td>' +
            '<td><input  type="number" name="" data-rule="required;integer;range(0~);" class="nums" onblur="totalNums(this)"></td>' +
            '<td><input  type="number" data-rule="required;range(0~);" name="" onblur="calMoney(this)"  class="unit-price"></td>' +
            '<td class="subtotal"></td>' +
            '<td><textarea rows="2" class="remarks" cols="20"></textarea></td>' +
            '<td> <button type="button" class="btn btn-primary" onclick="addRow()">添加</button><button type="button" class="btn btn-default" onclick="delRow(this)" >删除</button> </td>' +
            '</tr>';
    $('#table tbody tr:eq(' + lens + ')').after(tempTr);
}

//计算总数量
function totalNums(obj) {
    var len = $('#table tr').length;
    var total = 0;
    if (obj != null) {
        calMoney(obj);
    }
    for (var i = 1; i < len - 1; i++) {
        var nums = $('#table tr:eq(' + i + ') .nums').val();
        nums = getNumValue(nums);
        if (nums == false || nums < 0) {
            total = false;
            return false;
        }
        total += nums;
    }
    if (total != false) {
        $(".totalnums").text(total);
        $("#allNums").val(total);
    }
}

function getNumValue(num) {
    if (!isNaN(num) && num != "") {
        num = parseFloat(num);
        var a = isPositiveInteger(num)
        if (a == false) {
            num = false;
        }
    } else {
        num = false;
    }
    return num;
}

function isInteger(obj) {
    return obj % 1 === 0
}

function isPositiveInteger(s) { //是否为正整数
    var re = /^[0-9]+$/;
    return re.test(s)
}
// 小计
function calMoney(obj) {
    var total = 0;
    var nums = $(obj).parent().parent().find(".nums").val();
    var nuitprice = $(obj).parent().parent().find(".unit-price").val();
    if (nuitprice == "") {
        return false;
    }
    nuitprice = parseFloat(nuitprice);
    nums = getNumValue(nums);
    if (nums == false) {
        return false;
    }
    total = nuitprice * nums;
    total = total.toFixed(2);
    $(obj).parent().parent().find(".subtotal").text(total);
    calTotalMoneys();
}
// 计算总金额
function calTotalMoneys() {
    var len = $('#table tr').length;
    var total = 0;
    for (var b = 1; b < len - 1; b++) {
        var str = '#table tr:eq(' + b + ') .subtotal';
        var a = $(str).text();
        if (a == "") {
            a = 0;
        }
        a = parseFloat(a);
        if (a == "NaN" || a == "" || a == undefined) {
            a = 0;
        }
        total += a;
    }
    $("#table #allMoney").text(total);
    var rate = $("#c-rate").val();
    rate = parseFloat(rate);
    var totalMoney = total * (1 + rate / 100);
    // var totalMoney = total;
    $("#money").val(total);
    totalMoney = totalMoney.toFixed(2);
    $("#totalMoney").text(totalMoney);
    $("#totalMoneys").val(totalMoney);

}

function submitData() {

    var data = $("#add-form").serialize();
    // console.log(data)
    if ($("#c-supId").val() == '') {
        Toastr.error(__("Please select a merchant"));
        return false;
    }
    if ($("#hose-fist").val() == 0) {
        Toastr.error(__("Please select a warehouse"));
        return false;
    }
    $('#add-form').isValid(function (v) {
        // console.log(v)
        if (v == true) {
            var len = $("#table tr").length;
            var arr = new Array();
            var arrtep = new Array();
            var c = [];
            for (var i = 1; i < len - 1; i++) {
                var id = $("#table tr:eq(" + i + ")").find('.find').attr("data-id");
                if (id == "") {
                    Toastr.error(__("Please select a product"));
                    return false;
                }
                //判断购买数量是否大于库存 start
                var inventory = $("#table tr:eq(" + i + ")").find('.inventory').text() //当前行的商品库存
                var nums = $("#table tr:eq(" + i + ")").find('.nums').val(); //当前行的购买数量
                if (parseInt(nums) > parseInt(inventory)) {
                    alert('购买数量不能大于当前库存(序号' + i + '产品)');
                    return
                }
                //判断购买数量是否大于库存 end
                var data_id = $("#table tr:eq(" + i + ")").find('.prid').attr("data-id");
                var unitPrice = $("#table tr:eq(" + i + ")").find('.unit-price').val();
                var subtotal = $("#table tr:eq(" + i + ")").find('.subtotal').text();
                var unit = $("#table tr:eq(" + i + ")").find('.unit').text();
                var remarks = $("#table tr:eq(" + i + ")").find('.remarks').val();
                var b = i - 1;
                console.log(data_id);
                if (!data_id) {
                    data_id = "";
                    console.log(data_id)
                }
                arr.push({
                    "product_id": id,
                    "price": unitPrice,
                    "nums": nums,
                    "subtotal": subtotal,
                    "unit": unit,
                    "remarks": remarks,
                    "data_id": data_id
                });
            }
            var temp = JSON.stringify(arr);
            resutlData = data + "&" + "product=" + temp;
            // data.push({"name":"row['product']","value":temp});
            // var resutlData=JSON.stringify(data);
            Fast.api.ajax({
                // url:'purchase/order/edit/type/2',
                data: resutlData
            }, function (data, ret) {
                //成功的回调

                if (data.result = "success") {

                    layer.msg('成功提交', {
                        time: 2000, //2s后自动关闭
                        end: function () {
                            location.reload();
                        }
                    });
                }
                // console.log(data);
                // return false;
            }, function (data, ret) {
                //失败的回调
                // alert(ret.msg);
                return false;
            });
        }
    })

}

//作废销售单
function abandon(ids) {
    var str = "<div  style='width:80%;margin-left:auto;margin-right:auto'><textarea class='reason' rows='3' cols='38'></textarea></div>";
    layer.open({
        id: 1,
        type: 1,
        title: '请输入作废理由',
        skin: 'layui-layer-rim',
        area: ['450px', '300px'],

        content: str,
        btn: ['保存', '取消'],
        btn1: function (index, layero) {
            var reason = $(".reason").val().trim();
            if (reason == null || reason == '' || reason == undefined) {
                layer.alert('请输入作废理由')
                return false;
            } else {

                //执行作废销售单操作
                Fast.api.ajax({
                    url: 'ykjp/sell/selllist/abandon',
                    data: {
                        'ids': ids,
                        'reason': reason
                    }
                }, function (data, ret) {
                    //成功的回调
                    if (data.result = "success") {

                        layer.msg('成功提交', {
                            time: 2000, //2s后自动关闭
                            end: function () {
                                location.reload();
                            }
                        });
                    }
                    // console.log(data);
                    // return false;
                }, function (data, ret) {
                    //失败的回调
                    layer.alert(data.result);
                    return false;
                });

            }

        },
        btn2: function (index, layero) {
            layer.close(index);
        }

    });
}

function Anti(id) {
    Fast.api.ajax({
        url: "ykjp/sell/selllist/Anti?ids=" + id,
    }, function (data, ret) {
        //成功的回调

        if (data.result = "success") {
            location.reload();
        }
    }, function (data, ret) {
        Layer.alert(ret.msg);
        return false;
    });
}

// jQuery('body').delegate('#prind', 'click', function () {
//     var selector = Boolean(jQuery('body').find(".prindBody")) ? jQuery('body').find(".prindBody") : jQuery('body').find(".prindBody");
//     jQuery(selector).print({
//         addGlobalStyles: true,
//         stylesheet: '/assets/css/print.css',
//         rejectWindow: true,
//         noPrintSelector: ".no-print",
//         iframe: true,
//         append: null,
//         prepend: '<div style="text-align: center;font-size: 25px;padding-bottom:20px">销售单 </div>'
//     });
//     return false;
// });

function printPdf() {
    var headerTitle = $(".panel-heading").text();
    $(".panel-heading").text("销售单").css({
        "width":"200px",
        "margin":"0 auto",
        "font-size":"50px",
    });
    $(".prindBody .print-row,.prindBody .code label,.prindBody .print-row,.prindBody .code div").removeClass("col-xs-12").css({"float":"left"});
    $(".prindBody .print-row").removeClass("col-xs-12").addClass("col-xs-6").css({"float":"left"});
    $(".prindBody .print-row div , .prindBody .print-row label,.prindBody .print-remark div,.prindBody .print-remark label").removeClass("col-xs-12").css({"float":"left"});
    $(".print-total .print-total-row .print-row").removeClass("col-xs-12").css({"float":"right","width":"30%","margin-right":"-10%"});
    $(".print-total-row .print-row label,.print-total-row .print-row div").removeClass("col-xs-12");
    $(".no-print").css('display','none');
    $("#ribbon").css('display','none');
    window.print();
    $(".prindBody .print-row,.prindBody .code label,.prindBody .print-row,.prindBody .code div").addClass("col-xs-12").removeAttr("style");
    $(".prindBody .print-row").removeClass("col-xs-6").addClass("col-xs-12").removeAttr("style");
    $(".prindBody .print-row div , .prindBody .print-row label,.prindBody .print-remark div,.prindBody .print-remark label").addClass("col-xs-12").removeAttr("style");

    $(".print-total .print-total-row .print-row").addClass("col-xs-12").removeAttr("style");
    $(".print-total-row .print-row label,.print-total-row .print-row div").addClass("col-xs-12");

    $(".panel-heading").text(headerTitle).removeAttr("style");
    $(".no-print").css('display','block');
    $("#ribbon").css('display','block');
}